package com.hxd.buybooksystem.ui.fragment

import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.view.MotionEvent
import android.view.View
import cn.bmob.v3.listener.FindListener
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.exception.BmobException
import com.hxd.buybooksystem.uitls.L
import com.hxd.buybooksystem.R
import com.hxd.buybooksystem.adapter.IndexBookAdapter
import com.hxd.buybooksystem.base.common.MyLazyFragment
import com.hxd.buybooksystem.bean.Banner
import com.hxd.buybooksystem.bean.BookInfo
import com.hxd.buybooksystem.handle.GlideImageLoader
import com.hxd.buybooksystem.ui.activity.DetailsPageActivity
import com.hxd.buybooksystem.ui.activity.MainActivity
import com.hxd.tabactivityfragment.util.ThreadUtil
import com.youth.banner.BannerConfig
import com.youth.banner.listener.OnBannerListener
import kotlinx.android.synthetic.main.fragment_index.*
import org.jetbrains.anko.support.v4.startActivity

import java.util.ArrayList

/**
 *  项目名：    BuyBookSystem
 *  包名：      com.hxd.buybooksystem.ui.fragment
 *  文件名:     IndexFragment
 *  创建者:     HXD
 *  创建时间:   2019/5/28 20:19
 *  描述:       首页
 */

class IndexFragment : MyLazyFragment<MainActivity>() {

    val banners by lazy { ArrayList<Banner>() }
    val bookInfos by lazy { ArrayList<BookInfo>() }

    //设置单例静态方法
    companion object {
        fun newInstance(): IndexFragment {
            return IndexFragment()
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_index
    }

    override fun getTitleBarId(): Int {
        return R.id.tb_title_home
    }


    override fun initView() {
        initBanner()
        loadBookInfo()
    }

    override fun initData() {

    }

    /**
     * 初始化轮播图
     */
    private fun initBanner() {
        val bannerQuery = BmobQuery<Banner>()
        bannerQuery.findObjects(object : FindListener<Banner>() {
            override fun done(lists: MutableList<Banner>, e: BmobException?) {
                ThreadUtil.runOnMainThread(Runnable {
                    if (e == null) {
//                        L.i("Banner查询成功, $lists")
                        val images = ArrayList<String>()
                        val titles = ArrayList<String>()
                        lists.forEach {
                            banners.add(it)
                            it.image?.let { image -> images.add(image) }
                            titles.add(it.name)
                        }
                        banner.setImageLoader(GlideImageLoader())
                        banner.setImages(images)
                        banner.setBannerTitles(titles)
                        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE)
//                        L.i("images $images")
                        banner.setDelayTime(3000)
                        banner.start()
                    } else {
                        L.i("Banner查询失败：" + e.errorCode)
                    }
                })
            }
        })

        banner.setOnBannerListener {
            L.i("你点击了第${it}个图, objectId:${banners[it].imageObjectId}")
            val objectId = banners[it].imageObjectId!!.trim()
            startActivity<DetailsPageActivity>("objectId" to objectId)
        }
    }

    /**
     * 设置RecyclerView
     */
    private fun setRecyclerView() {
        //设置适配器
        val goodBookAdapter = IndexBookAdapter(bookInfos)
        recycler_good_book.adapter = goodBookAdapter

        //将数据打乱顺序
        bookInfos.shuffle()
        val hotBookAdapter = IndexBookAdapter(bookInfos)
        recycler_hot_book.adapter = hotBookAdapter

        //构造 LinearLayputManager，并设置方向。LinearLayputManager效果类似ListView。
        val recyclerViewLayoutManager = GridLayoutManager(context, 3)
        val recyclerViewLayoutManager2 = GridLayoutManager(context, 3)
        //设置滑动方向：横向
        recyclerViewLayoutManager.orientation = LinearLayoutManager.VERTICAL
        recyclerViewLayoutManager2.orientation = LinearLayoutManager.VERTICAL
        recycler_good_book.layoutManager = recyclerViewLayoutManager
        recycler_hot_book.layoutManager = recyclerViewLayoutManager2

        goodBookAdapter.setOnItemClickLitener(object : IndexBookAdapter.OnItemClickLitener {
            override fun onItemClick(position: Int, bookInfo: BookInfo) {
                startActivity<DetailsPageActivity>("objectId" to bookInfo.objectId)
//                L.i("indexObjectId : ${bookInfo.objectId}")
            }
        })

        hotBookAdapter.setOnItemClickLitener(object : IndexBookAdapter.OnItemClickLitener {
            override fun onItemClick(position: Int, bookInfo: BookInfo) {
                startActivity<DetailsPageActivity>("objectId" to bookInfo.objectId)
            }
        })
    }

    private fun loadBookInfo() {
        val bannerQuery = BmobQuery<BookInfo>()
        bannerQuery.findObjects(object : FindListener<BookInfo>() {
            override fun done(lists: MutableList<BookInfo>, e: BmobException?) {
                ThreadUtil.runOnMainThread(Runnable {
                    if (e == null) {
//                        L.i("IndexBookInfo查询成功, $lists")
                        lists.forEach {
                            bookInfos.add(it)
                        }
                        setRecyclerView()
                    } else {
                        L.i("IndexBookInfo查询失败：" + e.errorCode)
                    }
                })
            }
        })
    }

    override fun isStatusBarEnabled(): Boolean {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled()
    }
}